<!--
 * @Date: 2024-03-20 10:20:27
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-12-04 15:31:41
 * @Description: 修改或添加表单
-->
<template>
	<el-form
		ref="menuFormRef"
		class="menu-info-form rk-form"
		:model="formModal"
		:rules="formRules"
		label-width="120px"
	>
		<el-row >
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单类型" prop="menuType">
					<el-radio-group v-model="formModal.menuType" button-style="solid" @change="menuTypeChange">
						<el-radio-button v-for="item in menuTypeOptions"
							:key="item.value"
							:label="item.label"
							:value="item.value"
							:disabled="item.disabled"
						>
						</el-radio-button>
					</el-radio-group>
				</el-form-item>
			</el-col>
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单名称" prop="menuName">
					<el-input v-model="formModal.menuName" placeholder="请输入菜单名称" @blur="menuNameBlur" />
				</el-form-item>
			</el-col>
		</el-row>
		<el-row >
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单编码" prop="menuTempCode">
					<el-input v-model="formModal.menuTempCode" placeholder="请输入菜单编码">
							<template v-if="formModal.parentId" #prepend>{{ formModal.parentId }}</template>
					</el-input>
				</el-form-item>
			</el-col>
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单别名" prop="menuAlias">
					<el-input v-model="formModal.menuAlias" placeholder="请输入菜单别名" />
				</el-form-item>
			</el-col>
		</el-row>
		<el-row >
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单排序" prop="menuOrder">
					<el-input-number style="width: 100%" v-model="formModal.menuOrder" placeholder="请输入菜单排序" />
				</el-form-item>
			</el-col>
			<el-col :span="formConfig.col.span">
				<el-form-item label="权限标识" prop="permission">
					<el-input v-model="formModal.permission" placeholder="请输入权限标识" />
				</el-form-item>
			</el-col>
		</el-row>
		<el-row >
			<el-col :span="formConfig.col.span">
				<el-form-item label="菜单状态" prop="status">
					<el-radio-group button-style="solid" v-model="formModal.status">
						<el-radio-button
							v-for="item in MENU_STATUS_OPTIONS"
							:key="item.value"
							:value="item.value"
							:label="item.label"
						>
						</el-radio-button>
					</el-radio-group>
				</el-form-item>
			</el-col>
			<el-col v-if="!isButtonType" :span="formConfig.col.span">
				<el-form-item label="菜单图标" prop="icon">
					<IconSelector placeholder="请输入菜单图标" v-model="formModal.icon" />
				</el-form-item>
			</el-col>
		</el-row>
		<template v-if="!isButtonType">
			<el-row >
				<el-col :span="formConfig.col.span">
					<el-form-item label="路由名称" prop="routerName">
						<el-input v-model="formModal.routerName" placeholder="请输入路由名称" @blur="routerNameBlur" />
					</el-form-item>
				</el-col>
				<el-col :span="formConfig.col.span">
					<el-form-item label="是否显示" prop="invisible">
						<el-radio-group button-style="solid" v-model="formModal.invisible">
							<el-radio-button v-for="item in invisibleOptions"
								:key="item.value"
								:value="item.value"
								:label="item.label"
							>
							</el-radio-button>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="formConfig.col.span">
					<el-form-item label="路由地址" prop="routerPath">
						<el-input v-model="formModal.routerPath" placeholder="请输入路由地址" />
					</el-form-item>
				</el-col>
				<el-col :span="formConfig.col.span">
					<el-form-item label="重定向地址" prop="routerRedirect">
						<el-input v-model="formModal.routerRedirect" placeholder="请输入重定向地址" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="24">
					<el-form-item label="组件地址" prop="routerComponent">
						<!-- <el-input v-model="formModal.routerComponent" placeholder="请输入组件地址" /> -->
						<el-autocomplete
							style="width: 100%"
							:teleported="false"
							v-model="formModal.routerComponent"
							:fetch-suggestions="querySearch"
							clearable
							placeholder="请输入组件地址"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="24">
					<el-form-item label="外链地址" prop="routerLink">
						<el-input v-model="formModal.routerLink" placeholder="请输入外链地址" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="24">
					<el-form-item label="内嵌地址" prop="iframeSrc">
						<el-input v-model="formModal.iframeSrc" placeholder="请输入内嵌地址" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="24">
					<el-form-item label="路由参数" prop="routerParams">
						<el-input v-model="formModal.routerParams" placeholder="请输入路由参数，示例：id=12&name=test" @blur="routerParamsBlur" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row >
				<el-col :span="24">
					<el-form-item label="请求地址" prop="routerParams">
						<el-input v-model="formModal.fullUrl" placeholder="请求地址" disabled readonly />
					</el-form-item>
				</el-col>
			</el-row>
		</template>
		<el-row >
			<el-col :span="24">
				<el-form-item label="菜单备注" prop="remark">
					<el-input v-model="formModal.remark" placeholder="请输入菜单备注" type="textarea" :rows="3" resize="none"/>
				</el-form-item>
			</el-col>
		</el-row>
		<el-row  :gutter="12">
			<el-col :span="12">
				<el-form-item label="权限接口" prop="remark">
					<el-input :spellcheck="false" v-model="formModal.url" placeholder="请输入菜单备注" type="textarea" :rows="10" resize="none"/>
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-tag v-for="item in urlList" style="margin: 0 8px 8px 0;">
					{{ item }}
				</el-tag>
			</el-col>
		</el-row>
	</el-form>
</template>

<script setup>
import { XEUtils, IsUtils } from '@/utils';
import { IconSelector } from '@/components/rk-icon'
import { MENU_TYPE_ENUMS, MENU_INVISIBLE_ENUMS, MENU_TYPE_CONS } from '@/enums/enums-menu.js';
import { onMounted } from 'vue';

import { useEnv } from '@/hooks/useEnvHook'

// 可选的组件路径
const layouModules = import.meta.glob('@/layout/routerView/*.{vue,tsx}');
const viewsModules = import.meta.glob('@/views/**/*View.{vue,tsx}');
const dynamicViewsModules = Object.assign({}, { ...layouModules }, { ...viewsModules });

const props = defineProps({
	// 父节点
	parentNode: { type: Object },
	// 状态  add | edit
	btnTypeCode: { type: String },
	// 回显数据
	echoFormData: { type: Object },
});

// 按钮类型的选项数据
const MENU_STATUS_OPTIONS = [
	{value: 1, label: '启用', echo: '已启用', tagType: 'danger'},
	{value: 2, label: '停用', echo: '未启用', tagType: ''},
]

let loadComponentList = []

onMounted(() => {
	loadComponentList = Object.keys(dynamicViewsModules).map(item => {
		return { value: item.replace(/^\/src\/views/, '').replace(/^\/src/, '').replace(/.vue$/, '') }
	}).filter(item => {
		return checkComponentPath(item.value)
	}).filter(item => {
		if (useEnv().isProdEnv) {
			return !item.value.includes('examples')
		} else {
			return true
		}
	})
})

const checkComponentPath = (path) => {
	if (path.startsWith('/custom')) {
		return path.includes(useEnv().envMode)
	} else {
		return true
	}
}


// 是否编辑模式
const isEditMode = computed(() => {
	return !!formModal.menuId
})
// 是否为按钮类型
const isButtonType = computed(() => {
	return formModal.menuType === MENU_TYPE_CONS.BUTTON.value;
});

// ----- 菜单类型相关
const menuTypeOptions = reactive({
	0: { ...MENU_TYPE_ENUMS.options['0'], disabled: false },
	// 1: { ...MENU_TYPE_ENUMS.options['1'], disabled: false },
});
// ----- 是否显示相关
const invisibleOptions = ref([MENU_INVISIBLE_ENUMS.options['1'], MENU_INVISIBLE_ENUMS.options['0']]);

// ----- 表单操作相关
const btnFormModal = {
	// 菜单ID
	menuId: '',
	// 菜单类型 0-菜单 1-按钮
	menuType: 0,
	// 菜单编码
	menuCode: '',
	// 菜单名称
	menuName: '',
	// 菜单别名
	menuAlias: '',
	// 菜单排序
	menuOrder: 1,
	// 是否将作为菜单：0-隐藏 1-显示
	invisible: 1,
	// 权限标识
	permission: '',
	// 菜单备注
	remark: '',
	// 父级菜单
	parentId: '',
	// 菜单状态 1-启用 2-停用
	status: '1',
	// 菜单级次
	levelNo: 2,
	// 区划编码
	adCode: '',
	//
	menuTempCode: ''
};
const menuFormModal = {
	...btnFormModal,
	// 菜单URL
	url: '',
	// 菜单图标
	icon: '',
	// 路由访问地址
	routerPath: '',
	// 路由名称
	routerName: '',
	// 路由外链地址
	routerLink: '',
	// 路由重定向地址
	routerRedirect: '',
	// 路由组件地址
	routerComponent: '',
	// iframe加载地址
	iframeSrc: '',
	// 路由额外参数
	routerParams: '',
	// 全路径
	fullUrl: '',
};
const formModal = reactive(XEUtils.clone(menuFormModal, true));
const formRules = reactive({
	menuCode: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
	menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
	routerName: [{ required: true, message: '请输入路由名称', trigger: 'blur' }],
	routerPath: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
	menuTempCode: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
	routerComponent: [{ required: true, message: '请输入组件地址', trigger: 'change' }],
});
const formConfig = reactive({
	col: { lg: 12, md: 12, sm: 24, span: 12 },
});
/** 加载表单数据 */
const loadForm = () => {
	Reflect.ownKeys(formModal).forEach((key) => {
		const echoFormValue = props.echoFormData[key];
		let value = IsUtils.isNotEmpty(echoFormValue) ? echoFormValue : formModal[key];
		formModal[key] = XEUtils.clone(value, true)
		if (key === 'icon' && value && !(value.startsWith('ele-') || value.startsWith('iconfont') || value.startsWith('rk-'))) {
			formModal[key] = XEUtils.clone(`${value}`, true);
		}
	});
	setMenuSomeInfo();
	setMenuTypeInfo();
};
const setMenuSomeInfo = () => {
	const { echoFormData: echoForm } = props;
	if (!formModal.menuId) {
		const { menuCount, buttonCount } = echoForm;
		let menuOrder = echoForm.menuOrder;
		if (formModal.menuType === 0) {
			menuOrder = menuCount + 1;
		} else {
			menuOrder = buttonCount + 1;
		}
		formModal.menuOrder = menuOrder;
	} else {
		formModal.menuTempCode = formModal.menuCode.replace(formModal.parentId, '')
	}
};
const setMenuTypeInfo = () => {
	const { echoFormData: echoForm } = props;
	// const { menuType } = echoForm
	if (echoForm.menuId) {
		// if (menuType === MENU_TYPE_CONS.MENU.code) {
		//   menuTypeOptions[MENU_TYPE_CONS.MENU.code].disabled = false
		//   menuTypeOptions[MENU_TYPE_CONS.BUTTON.code].disabled = true
		// }
		// if (menuType === MENU_TYPE_CONS.BUTTON.code) {
		//   menuTypeOptions[MENU_TYPE.MENU.code].disabled = true
		//   menuTypeOptions[MENU_TYPE_CONS.BUTTON.code].disabled = false
		// }
	} else {
		if (echoForm.menuCount != 0) {
			menuTypeOptions[MENU_TYPE_CONS.MENU.value].disabled = false;
			// menuTypeOptions[MENU_TYPE_CONS.BUTTON.value].disabled = true;
		} else {
			menuTypeOptions[MENU_TYPE_CONS.MENU.value].disabled = false;
			// menuTypeOptions[MENU_TYPE_CONS.BUTTON.value].disabled = false;
		}
	}
};
// 权限接口数组
const urlList = computed(() => {
	if (formModal.url) {
		return formModal.url.split(';').filter(item => item !== '')
	} else {
		return []
	}
})
/** 菜单名称输入失去焦点 */
const menuNameBlur = () => {
	const { menuName } = formModal;
	// 设置别名
	formModal.menuAlias = menuName;
};
/** 菜单类型发生变化 */
const menuTypeChange = () => {
	const { parentNode, echoFormData: echoForm } = props;
	const { menuType, routerName } = formModal;
	if (menuType === MENU_TYPE_CONS.BUTTON.value) {
		if (echoForm.permission) {
			formModal.permission = echoForm.permission;
		} else {
			formModal.permission = `${parentNode.routerName}:`;
		}
	} else {
		if (echoForm.permission) {
			formModal.permission = echoForm.permission;
		} else {
			formModal.permission = routerName;
		}
	}
	// setMenuSomeInfo()
};
/** 路由名称发生变化 */
const routerNameBlur = () => {
	const { routerName, menuType, parentId } = formModal;
	// 设置权限标识
	let permission = routerName;
	if (menuType === MENU_TYPE_CONS.MENU.value) {
		permission = permission ? `${permission}:list` : '';
	}
	formModal.permission = permission;
	formModal.routerPath = !parentId ? `/${routerName}` : routerName;
	formModal.fullUrl = getFullUrl()
};
/** 路由参数发生变化 */
const routerParamsBlur = () => {
	formModal.fullUrl = getFullUrl();
};

/** 获取菜单全地址 */
const getFullUrl = () => {
	const { routerName, routerParams, menuId, fullUrl } = formModal;
	const { parentNode: { extraInfo: { nextFullUrl }, menuId: parentId } } = props;
	let resultUrl = nextFullUrl
	if (isEditMode.value) {
		// 如果没有选择父节点
		if (!nextFullUrl || (menuId === parentId)) {
			const fullURL = fullUrl.split('?')[0]
			resultUrl = fullURL.slice(0, fullURL.lastIndexOf('/'))
		}
	}
	resultUrl = routerName ? `${resultUrl}/${routerName}` : resultUrl
	resultUrl = routerParams ? `${resultUrl}?${routerParams}` : resultUrl
	return resultUrl
}
// ----- 路由参数相关

// 表单的模板引用对象
const menuFormRef = ref();
/** 获取表单数据 */
const getFormData = () => {
	let resultData = XEUtils.clone(toRaw(formModal), true);
	const iconValue = resultData['icon'];
	// resultData['icon'] = iconValue ? iconValue.replace('rk-', '') : iconValue;
	// 过滤url中的换行，空格，回车
	resultData['url'] = resultData.url ? resultData.url.replace(/[\n\s\r]+/g, '') : '';
	resultData.menuCode = `${resultData.parentId}${resultData.menuTempCode}`
	delete resultData.menuTempCode
	return resultData;
};
/** 校验表单信息 */
const validateForm = () => {
	return new Promise((resolve) => {
		menuFormRef.value.validate((valid, invalidFields) => {
			resolve(valid);
		});
	});
};

const querySearch = (value, callback) => {
	const result = value
		? loadComponentList.filter(createFilter(value))
		: loadComponentList
	callback(result)
}
const createFilter = (value) => {
	return (item) => {
		return item.value.toLowerCase().includes(value.toLowerCase())
	}
}


loadForm();

defineExpose({
	getFormData,
	validateForm,
});
</script>

<style lang="scss" scoped>
.menu-info-form {
	padding-right: 50px;
	:deep(.el-row) {
		margin-bottom: 20px;
	}
}
</style>
